package com.chanjiedata.changbs.module.main;


import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.base.BaseFragment;
import com.chanjiedata.changbs.base.MainApplication;
import com.chanjiedata.changbs.bean.ServiceBean;
import com.chanjiedata.changbs.dialog.HomeFirstDialog;
import com.chanjiedata.changbs.help.UserHelper;
import com.chanjiedata.changbs.module.createcard.CreateShopListActivity;
import com.chanjiedata.changbs.module.mine.RenZhenActivity;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.WebApis;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Index;
import com.chanjiedata.changbs.proto.MemberOuterClass;
import com.chanjiedata.changbs.proto.Recharge;
import com.chanjiedata.changbs.utlis.TimeUtils;
import com.chanjiedata.changbs.utlis.ValidateUtils;
import com.chanjiedata.changbs.view.BannerImageHoderView;
import com.chanjiedata.changbs.view.LoadMoreBottomView;
import com.chanjiedata.changbs.web.ui.WebViewActivity;
import com.example.havi.helper.ChatHelper;
import com.example.havi.interfaces.LoginCallBack;
import com.example.havi.ui.ChatActivity;
import com.google.protobuf.InvalidProtocolBufferException;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import kale.ui.view.dialog.EasyDialog;


/**
 * Created by Administrator on 2018/2/2 0002.
 */

public class HomeFragment extends BaseFragment {
    // 广告轮播
    @BindView(R.id.home_convenient_banner)
    ConvenientBanner convenientBanner;
    // 下拉刷新
    @BindView(R.id.home_refreshLayout)
    TwinklingRefreshLayout mRefreshLayout;
    @BindView(R.id.tv_liu_sui_number)
    TextView tvLiuSuiNumber;  // 流水排名
    @BindView(R.id.tv_ji_huo_number)
    TextView tvJiHuoNumber;  // 激活排名
    @BindView(R.id.tv_home_title)
    TextView tvHomeTitle;
    @BindView(R.id.tv_home_today_income)
    TextView tvHomeTodayIncome;
    @BindView(R.id.tv_home_today_income_rate)
    TextView tvHomeTodayIncomeRate;
    @BindView(R.id.iv_home_today_income_rate)
    ImageView ivHomeTodayIncomeRate;
    @BindView(R.id.tv_home_yesterday_income)
    TextView tvHomeYesterdayIncome;
    @BindView(R.id.tv_home_today_trading)
    TextView tvHomeTodayTrading;
    @BindView(R.id.tv_home_today_trading_rate)
    TextView tvHomeTodayTradingRate;
    @BindView(R.id.iv_home_today_trading_rate)
    ImageView ivHomeTodayTradingRate;
    @BindView(R.id.tv_home_yesterday_trading)
    TextView tvHomeYesterdayTrading;
    @BindView(R.id.tv_home_today_active)
    TextView tvHomeTodayActive;
    @BindView(R.id.tv_home_yesterday_active)
    TextView tvHomeYesterdayActive;
    @BindView(R.id.tv_home_yesterday_active_rate)
    TextView tvHomeYesterdayActiveRate;
    @BindView(R.id.iv_home_yesterday_active_rate)
    ImageView ivHomeYesterdayActiveRate;
    private List<Index.get_show_list.List> advDatas = new ArrayList<>(); // banner数据

    Unbinder unbinder; // bufferKnife绑定


    @Override

    protected int getLayoutId() {
        return R.layout.fragment_home;
    }


    @Override
    protected void initView() {
        initRefresh();   // 下拉刷新
        showAlert();
        mRefreshLayout.startRefresh();
    }

    /**
     * 用于设置首页title
     */
    private void initTitle() {
        NetworkManager.INSTANCE.post(Apis.memberDataInfo, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                MemberOuterClass.Member member = MemberOuterClass.Member.parseFrom(bytes);
                if (member.getIsApprove() == 0) {
                    tvHomeTitle.setText("请实名认证");
                    tvHomeTitle.setOnClickListener(view -> {
                        startActivity(RenZhenActivity.class);
                    });
                } else {
                    if (TextUtils.isEmpty(member.getMemberName())) {
                        // 获取当时时间是中午下午,还是晚上
                        String dateSx = TimeUtils.getDateSx();
                        tvHomeTitle.setText(dateSx + "," + member.getTruename());
                    } else {
                        // 获取当时时间是中午下午,还是晚上
                        String dateSx = TimeUtils.getDateSx();
                        tvHomeTitle.setText(dateSx + "," + member.getMemberName());
                    }
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

            }
        });
    }

    @Override
    protected void init() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }


    /**
     * 实例化下拉Refresh
     * *
     */
    private void initRefresh() {
        SinaRefreshView header = new SinaRefreshView(getContext());
        header.setArrowResource(R.mipmap.refresh_arrow);
        TextView refreshTextView = header.findViewById(com.lcodecore.tkrefreshlayout.R.id.tv);
        refreshTextView.setTextSize(14);
        header.setBackgroundResource(R.color.backgroundColor);
        mRefreshLayout.setHeaderView(header);
        LoadMoreBottomView bottom = new LoadMoreBottomView(getContext());
        mRefreshLayout.setBottomView(bottom);
        mRefreshLayout.setEnableLoadmore(false);
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                loadData();

            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                loadData();
            }
        });
    }


    /**
     * 加载数据项
     */
    private void loadData() {

        // 加载首页数据
        NetworkManager.INSTANCE.post(Apis.today_earnings, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                if (mRefreshLayout == null) return; // 防止请求延迟出现闪退
                Recharge.today_earnings today_earnings = Recharge.today_earnings.parseFrom(response);
                List<Recharge.today_earnings.Earningsinfo.List> lists = today_earnings.getEarningsInfo().getListList();
                Recharge.today_earnings.TopInfo topInfo = today_earnings.getTopInfo();
                tvHomeTodayIncome.setText(lists.get(0).getToday());
                tvHomeYesterdayIncome.setText(lists.get(0).getYesterday());
                tvHomeTodayIncomeRate.setText(lists.get(0).getRatio() + "%");
                if (lists.get(0).getRatio().contains("-")) {
                    tvHomeTodayIncomeRate.setTextColor(Color.parseColor("#ff41b595"));
                    ivHomeTodayIncomeRate.setBackgroundResource(R.mipmap.icon_down);
                } else {
                    tvHomeTodayIncomeRate.setTextColor(Color.parseColor("#FF5F3D"));
                    ivHomeTodayIncomeRate.setBackgroundResource(R.mipmap.icon_up);
                }

                tvHomeTodayTrading.setText(lists.get(1).getToday());
                tvHomeYesterdayTrading.setText(lists.get(1).getYesterday());
                tvHomeTodayTradingRate.setText(lists.get(1).getRatio() + "%");
                if (lists.get(1).getRatio().contains("-")) {
                    tvHomeTodayTradingRate.setTextColor(Color.parseColor("#ff41b595"));
                    ivHomeTodayTradingRate.setBackgroundResource(R.mipmap.icon_down);
                } else {
                    tvHomeTodayTradingRate.setTextColor(Color.parseColor("#FF5F3D"));
                    ivHomeTodayTradingRate.setBackgroundResource(R.mipmap.icon_up);
                }
                tvHomeTodayActive.setText(lists.get(2).getToday());
                tvHomeYesterdayActive.setText(lists.get(2).getYesterday());
                tvHomeYesterdayActiveRate.setText(lists.get(2).getRatio() + "%");
                if (lists.get(2).getRatio().contains("-")) {
                    tvHomeYesterdayActiveRate.setTextColor(Color.parseColor("#ff41b595"));
                    ivHomeYesterdayActiveRate.setBackgroundResource(R.mipmap.icon_down);
                } else {
                    tvHomeYesterdayActiveRate.setTextColor(Color.parseColor("#FF5F3D"));
                    ivHomeYesterdayActiveRate.setBackgroundResource(R.mipmap.icon_up);
                }
                tvLiuSuiNumber.setText(topInfo.getTrading());
                tvJiHuoNumber.setText(topInfo.getActivation());
                // 接口返回比较慢,以此来结束刷新请求
                mRefreshLayout.finishRefreshing();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });


        // 加载banner的数据
        NetworkManager.INSTANCE.post(Apis.get_banner, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                if (mRefreshLayout == null) return;

                Index.get_show_list data = Index.get_show_list.parseFrom(bytes);
                advDatas  = data.getAdvListList();
                Log.e("wang",advDatas.toString());
                initBanner(advDatas);
                // 接口返回比较慢,以此来结束刷新请求
                mRefreshLayout.finishRefreshing();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                if (mRefreshLayout == null) return;
                mRefreshLayout.finishRefreshing();
                showToast(errorMessage);
            }
        });


    }


    private void initBanner(List<Index.get_show_list.List> data) {
        convenientBanner.setPages(() -> new BannerImageHoderView(), data)
                .setPageIndicator(new int[]{R.mipmap.indicator_un_selected, R.mipmap.indicator_selected})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
        convenientBanner.startTurning(6000);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.home_category_one, R.id.home_category_two, R.id.home_category_three, R.id.home_category_four,
            R.id.title_bar_right_img_one, R.id.ll_service, R.id.ll_rank, R.id.rv_shou_yi, R.id.rv_jiao_yi, R.id.rv_ji_huo
    })
    public void onViewClicked(View view) {
        if (UserHelper.checkGoLogin(mContext)) return;
        switch (view.getId()) {
            case R.id.home_category_one:
                WebViewActivity.startActivity(mContext, WebApis.shopping);
                break;
            case R.id.home_category_two: // 我的伙伴
                startActivity(PartnerActivity.class);
                break;
            case R.id.home_category_three:  // 我的库存
                startActivity(MyMachineActivity.class);
                break;
            case R.id.home_category_four: // 业务办理
                if (UserHelper.getUser().getIs_approve() == 0) {
                    showToast("请先进行实名认证");
                    startActivity(RenZhenActivity.class);
                } else {
                    WebViewActivity.startActivity(mContext, WebApis.Business_application);
                }
                break;
            case R.id.ll_rank: // 排行榜
                startActivity(RankActivity.class);
                break;
            case R.id.ll_service: // 客服聊天
                startChat();
                break;
            case R.id.rv_shou_yi:
                ((MainActivity) getActivity()).viewPager.setCurrentItem(1);
                ((MainActivity) getActivity()).count.viewPager.setCurrentItem(0);
                break;
            case R.id.rv_jiao_yi:
                ((MainActivity) getActivity()).viewPager.setCurrentItem(1);
                ((MainActivity) getActivity()).count.viewPager.setCurrentItem(1);
                break;
            case R.id.rv_ji_huo:
                ((MainActivity) getActivity()).viewPager.setCurrentItem(1);
                ((MainActivity) getActivity()).count.viewPager.setCurrentItem(2);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initTitle();
    }

    private void startChat() {
        boolean login = ChatHelper.getInstance().isLogin();
        if (login) {
            // 打开客服聊天
            ServiceBean keFuInfo = UserHelper.getKeFuInfo();
            if (ValidateUtils.isValidate(keFuInfo)) {
                ChatActivity.startActivity(mContext, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
            } else {
                showToast("暂无客服信息");
            }
        } else {
            showToast("聊天登录中");
            MainApplication.getChatHelper().login(UserHelper.getUser().getChat_id(), UserHelper.getUser().getChat_pwd(), new LoginCallBack() {
                @Override
                public void onSuccess() {
                    //判断是否为客服
                    // 打开客服聊天
                    ServiceBean keFuInfo = UserHelper.getKeFuInfo();
                    if (ValidateUtils.isValidate(keFuInfo)) {
                        mContext.runOnUiThread(() -> showToast("人工客服回复时间：工作日9:00-12:00；13:30-18:00"));
                        ChatActivity.startActivity(mContext, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
                    } else {
                        mContext.runOnUiThread(() -> showToast("暂无客服信息"));
                    }
                }

                @Override
                public void onError(int code, String message) {
                    mContext.runOnUiThread(() -> showToast("聊天暂时登录失败"));
                }
            });
        }
    }


    private void showAlert() {
        Index.get_agreement.Builder builder = Index.get_agreement.newBuilder();
        builder.setType("act_alert");
        NetworkManager.INSTANCE.post(Apis.get_agreement, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Index.get_agreement agreement = Index.get_agreement.parseFrom(response);
                Log.e("mango", "onOk: " + agreement );
                if (agreement.getActState().equals("1")) {
                    HomeFirstDialog.Builder builder = new HomeFirstDialog.Builder(mContext);
                    builder.setContent(agreement.getContent());
                    EasyDialog build = builder.build();
                    build.show(getChildFragmentManager());
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

            }
        });
    }


}
